import sys
def cmp(s1, s2):
    return int(s1[0]) - int(s2[0]);

M = int(sys.argv[1]);
result = sys.argv[2];
finalResult = sys.argv[3];
K = int(sys.argv[4]);

labeled_dict = {};
predictDict = {};
for i in range(M):
    queryID = str(i+1);
    labeled_dict[queryID] = {};
    predictDict[queryID] = [];

labeled = open('/home/wangshuxin/app_search/label_data/label_from_log.txt', 'r');

c = 0;
for line in labeled:
    li = line.strip().split('|');
    c += 1;
    queryID = str(c);
    l = len(li);
    for i in range(1,l):
        cli = li[i].split(':');
        labeled_dict[queryID][cli[1]] = int(cli[2]);

labeled.close();
predict = open(result, 'r');
for line in predict:
    li = line.strip().split('\t');
    queryID = li[0];
    queryString = li[1];
    #appString = li[4];
    appString = 'appString'
    appID, s = li[2], float(li[3]);
    predictDict[queryID].append((s,appID, queryString, appString));
predict.close();

raw_dict = {};
raw_result = open('results', 'r');
for line in raw_result:
    li = line.split('\t');
    
    appString = li[4];
    appID = li[2]
    raw_dict[appID] = appString;
raw_result.close();

finalResult = open(finalResult, 'w');
for queryID, value in sorted(predictDict.items(), cmp):
    value.sort(reverse=True);
    for  p ,pair in enumerate(value):
        if p >= K:
            break;
        s, appID, queryString, appString= pair;
        if labeled_dict[queryID].has_key(appID):
            finalResult.write('%s\t%s\t%s\t%s\n' % (queryID,  s, labeled_dict[queryID][appID], appID));
finalResult.close();

